<?php
defined('SYSPATH') OR die('No direct access allowed.');
/**
 * user.php
 * @author ranuandra
 *
 * 19 Agu 2011 10:28:32
 *
 * 
 */

class Controller_User Extends Kohana_Polreg
{
	public $auth_required = array('login', 'admin');
	public function action_index()
	{
		$users = ORM::factory('user')->find_all();
		$container = View::factory('user/index');
		$container->title = "Daftar User";
		$container->datas = $users;
		if(Request::current()->is_ajax() == $this->request)
		{	
			$container->ajax = 1;
			echo $container;
			exit;
		}
		else 
		{	$container->ajax = 0;
			$menu = View::factory('module/menu');
			$this->template->menu = $menu;
			$this->template->container = $container;
		}		
	}
	
	public function action_new()
	{
		$this->action_edit(0);
	}
	
	public function action_edit($id=0)
	{
		$area = ORM::factory('area')->find_all()->as_array('id', 'area');
		$userarea = ORM::factory('userarea')->where('user_id', '=', $id)->find_all()->as_array('user_id', 'area_id');
		
		$form = View::factory('user/form');
		
		$form->arealist = $area;
		$form->userarea = $userarea;
		$form->form = array('username' 	=> '',
							'password'	=> '',
							'password_confirm'	=> '',
							'email'				=>''
							);
		$form->title = "Edit User";
		if(Request::current()->is_ajax() == $this->request)
		{
			echo $form;
		}
		else 
		{
			$this->template->container = $form;
		}
	}
	
	public function action_save()
	{
		if(isset($_POST))
		{
	        try 
			{
	
				$user = ORM::factory('user');
				
				$user->create_user($_POST, array(
			 										'username',
													'password',
			 										'email',
			  									));
			  	if($_POST['level']==0)
			  	{
			  		$login_role = new Model_Role(array('name' =>'login'));
					$user->add('roles',$login_role);
			  	}
			  	else 
			  	{
			  		$login_role = new Model_Role(array('name' =>'login'));
					$user->add('roles',$login_role);
			  		$login_role = new Model_Role(array('name' =>'admin'));
					$user->add('roles',$login_role);
			  	}
			  	
				if(Request::current()->is_ajax() == $this->request)
				{
					$auto_render = FALSE;
					echo "sukses";
					exit;
				}
				else 
				{
					Request::current()->redirect(URL::base().'user');
				}
				
			}
			catch (ORM_Validation_Exception $e) {
				$errors = $e->errors('models');
				print_r($errors);
			}	
		}	
	}
}